package com.kotlin.android.ktx.utils

import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import androidx.core.app.ActivityCompat
import java.io.IOException
import java.io.InputStream


/**
 * Created by zl on 17/7/27.
 */

object ConfigUtils {

    /**
     * 返回manifest文件里的版本名（versionName）

     * @param context
     * *
     * @return
     */
    fun getVersionName(context: Context): String {
        /**
         * Binder机制导致
         * Binder的使用超出了一个进程的限制就会抛出TransactionTooLargeException这个异常
         */
        var version = "0.0.0"
        synchronized(ConfigUtils::class.java) {
            val packageManager = context.packageManager
            try {
                val packageInfo = packageManager.getPackageInfo(context.packageName, 0)
                version = packageInfo.versionName
            } catch (e: PackageManager.NameNotFoundException) {
                LogUtils.d(e.toString())
            }
            return version
        }
    }

    /**
     * 字符串版本比较函数

     * @param v1
     * *
     * @param v2
     * *
     * @return 如果v1大于v2，返回true，否则返回false
     */
    fun compareVersion(v1: String?, v2: String?): Boolean {
        if (v1 != null && v2 != null) {
            val sb1 = StringBuffer(v1)
            val sb2 = StringBuffer(v2)
            while (sb1.isNotEmpty() && sb2.isNotEmpty()) {
                val ver1 = getVerString(sb1)?:""
                val ver2 = getVerString(sb2)?:""
                try {
                    val version1 = Integer.parseInt(ver1)
                    val version2 = Integer.parseInt(ver2)
                    if (version1 == version2) {
                        continue
                    } else if (version1 > version2) {
                        return true
                    } else if (version1 < version2) {
                        return false
                    }
                } catch (e: NumberFormatException) {
                    return false
                }

            }
        }
        return false
    }

    /**
     * 获取版本号

     * @param str
     * *
     * @return
     */
    fun getVerString(str: StringBuffer?): String? {
        val ver: String?
        if (str == null) {
            return null
        }

        val pos = str.indexOf(".")
        if (pos == -1) {
            ver = str.toString()
            str.delete(0, str.length)
            return ver
        }
        ver = str.substring(0, pos)
        str.delete(0, pos + 1)
        return ver
    }

    /**
     * 获取设备的可用内存大小

     * @param context 应用上下文对象context
     * *
     * @return 当前内存大小
     */
    fun getDeviceUsableMemory(context: Context): Int {
        val am = context
                .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val mi = ActivityManager.MemoryInfo()
        am.getMemoryInfo(mi)
        // 返回当前系统的可用内存
        return (mi.availMem / (1024 * 1024)).toInt()
    }

    /**
     * 返回manifest文件里的版本号（versionCode）

     * @param context
     * *
     * @return
     */
    fun getVersionCode(context: Context): Int {
        var vCode = 0

        synchronized(ConfigUtils::class.java){
            val packageManager = context.packageManager
            try {
                val packageInfo = packageManager.getPackageInfo(context.packageName, 0)
                vCode = packageInfo.versionCode
            } catch (e: PackageManager.NameNotFoundException) {
                LogUtils.e(e.toString())
            }
        }

        return vCode
    }

    /**
     * 检查是否安装了sd卡

     * @return false 未安装
     */
    fun sdcardMounted(): Boolean {
        val state = Environment.getExternalStorageState()
        return state == Environment.MEDIA_MOUNTED && state != Environment.MEDIA_MOUNTED_READ_ONLY
    }

    /**
     * 返回网络连接,如果为空,无网络连接

     * @param context
     * *
     * @return
     */
    fun getNetworkInfo(context: Context): NetworkInfo {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val netinfo = cm.activeNetworkInfo
        return netinfo
    }

    /**
     * 从assets里获取相关配置信息
     */
    fun getFromAssets(context: Context, assetsName: String): String {

        var text= ""
        var inputStream: InputStream? = null
        try {
            inputStream = context.assets.open(assetsName)
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.read(buffer)
            text = String(buffer)
            //去掉/n
            text = text.trim()
            LogUtils.d(text)
        } catch (e: IOException) {
            LogUtils.e("Can not load file " + assetsName + "\n" + e.toString())
        } finally {
            FileUtils.closeSteam(inputStream)
        }
        if (TextUtils.isEmpty(text)) {
            return ""
        }
        return text
    }


    private val REQUEST_EXTERNAL_STORAGE = 1
    private val PERMISSIONS_STORAGE = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)

    @TargetApi(Build.VERSION_CODES.M)
    fun verifyStoragePermissions(activity: Activity?) {
        // Check if we have write permission
        val permission = ActivityCompat.checkSelfPermission(activity!!,
                Manifest.permission.READ_EXTERNAL_STORAGE)
        val permission1 = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (permission != PackageManager.PERMISSION_GRANTED || permission1 != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE)
        }
    }
}

